package com.cwt_taxi_xa.util;

import android.util.Log;

import java.util.Arrays;

/**
 * Created by undi on 2019/9/5 17:51
 */
public class ByteArrayUtil {
    private static String TAG = "ByteArrayUtil";
    /**
     * 获取验证码byte数组，基于905&XModem CRC16的校验算法
     */
    public static byte[] get2Crc16(byte[] arr_buff) {
        int count = arr_buff.length;
        int countLength = arr_buff.length -1;
        int crc = 0x00;
        while (--count >= 0) {
            crc = crc ^ arr_buff[countLength - count] << 8;
            int ii = 8;
            do {
                if ((crc & 0x8000) > 0) {
                    crc = crc << 1 ^ 0x1021;
                } else {
                    crc = crc << 1;
                }
            } while (--ii > 0);
        }
        return IntUtil.bigInt16ToBytes(crc&0xFFFF);
    }

    /**
     * 合并数组
     * @param first 第一个数组
     * @param rest 其它数组
     * @return
     */
    public static byte[] concatAll(byte[] first, byte[]... rest) {
        int totalLength = first.length;
        for (byte[] array : rest) {
            if (array != null) {
                totalLength += array.length;
            }
        }
        byte[] result = Arrays.copyOf(first, totalLength);
        int offset = first.length;
        for (byte[] array : rest) {
            if (array != null) {
                System.arraycopy(array, 0, result, offset, array.length);
                offset += array.length;
            }
        }
        return result;
    }


    public static byte[] reverse808Send(byte[]  buffer){
        byte[] newBuffer = new byte[buffer.length * 2];
        if(buffer != null){
            int expandLength = 0;
            for (int i = 0; i < buffer.length; i++) {
                if (buffer[i] == (byte)0x7D) {
                    //0x54 <————> 0x54 后紧跟一个0x01
                    //0x55 <————> 0x54 后紧跟一个0x02
                    newBuffer[i + expandLength] = 0x7D;
                    newBuffer[i + ++expandLength] = 0x01;
                }else if (buffer[i] == (byte)0x7E) {
                    newBuffer[i + expandLength] = 0x7D;
                    newBuffer[i + ++expandLength] = 0x02;
                } else {
                    newBuffer[i + expandLength] = buffer[i];
                }

            }
            return Tools.byteTobyte(newBuffer,0,buffer.length + expandLength);
        }
        Log.e(TAG,"error !!!!!!!!!!!! mcuReverseSend buffer:" + Tools.parseByte2HexStr(buffer));
        return buffer;
    }
}
